package com.longshen.dubbo.api.restful;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.longshen.dubbo.api.anno.LoginRequired;
import com.longshen.dubbo.api.base.Contents;
import com.longshen.dubbo.api.base.ErrorCode;
import com.longshen.dubbo.api.base.RestResult;
import com.longshen.dubbo.api.base.SessionBean;
import com.longshen.dubbo.api.exception.DubboApiException;
import com.longshen.dubbo.api.model.AdminMenu;
import com.longshen.dubbo.api.model.AdminRoleMenu;
import com.longshen.dubbo.api.model.AdminTrade;
import com.longshen.dubbo.api.model.AdminUser;
import com.longshen.dubbo.api.model.AdminUserRole;
import com.longshen.dubbo.api.restful.vo.LogInIn;
import com.longshen.dubbo.api.restful.vo.Meta;
import com.longshen.dubbo.api.restful.vo.RouteVo;
import com.longshen.dubbo.api.restful.vo.UserVO;
import com.longshen.dubbo.api.restful.vo.Userinfo;
import com.longshen.dubbo.api.service.AdminMenuService;
import com.longshen.dubbo.api.service.AdminRoleService;
import com.longshen.dubbo.api.service.AdminUserRoleService;
import com.longshen.dubbo.api.service.AdminUserService;
import com.longshen.dubbo.api.tools.ServletTools;
import com.longshen.dubbo.api.type.MenuType;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class LogInController {

	@Autowired
	private AdminUserService adminUserService;

	@Autowired
	private AdminMenuService adminMenuService;
	@Autowired
	private AdminRoleService adminRoleService;

	@Autowired
	private AdminUserRoleService adminUserRoleService;
	
	
	

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public RestResult<UserVO> login(@RequestBody LogInIn in) throws DubboApiException {

		AdminUser user = adminUserService.loginFind(in.getCellphone());
		if (user == null) {
			return RestResult.fail(ErrorCode.E_000001);
		}
		if (in.getPassword().equals(user.getPassword())) {
			RestResult<UserVO> rest = RestResult.success();
			/**
			 * 设置返回对象
			 */
			UserVO vo = new UserVO();
			BeanUtils.copyProperties(user, vo);
			rest.setData(vo);
			//获取角色
			AdminUserRole aur = adminUserRoleService.findByUserId(user.getId());
		    
			//获取交易权限
			List<AdminTrade>  trades=	adminRoleService.ownTreade(aur.getRoleId());
			StringBuffer  tradescodes=new StringBuffer();
			if(trades !=null && trades.size()>0) {
				trades.forEach(t->{
					tradescodes.append(t.getTradeCode()).append(",");
				});
			}
			
			/**
			 * 设置存储会话用户
			 */
			SessionBean sessionBean = new SessionBean();
			sessionBean.setUserid(user.getId());
			sessionBean.setUsername(user.getUsername());
			sessionBean.setNickname(user.getNickname());
			sessionBean.setRoleid(aur.getRoleId());
			sessionBean.setTradecodes(tradescodes.toString());

			HttpSession session = ServletTools.getSession(true);
			session.setAttribute(Contents.SESSION_BEAN, sessionBean);
			return rest;
		} else {
			RestResult rest = RestResult.newInstance();
			rest.setErrorCode(ErrorCode.E_000001);
			return rest;
		}

	}

	@LoginRequired
	@RequestMapping(value = "/userinfo", method = RequestMethod.GET)
	public RestResult<Userinfo> userInfo() {
		
		HttpSession session = ServletTools.getSession(false);
		SessionBean sessionBean = (SessionBean) session.getAttribute(Contents.SESSION_BEAN);
		Userinfo info = new Userinfo();
		BeanUtils.copyProperties(sessionBean, info);

		// 查询所有菜单
		List<AdminMenu> list = adminMenuService.listAll();
		if (StringUtils.isNotBlank(sessionBean.getRoleid())) {
			List<AdminRoleMenu> orederMenus = adminRoleService.roleMenus(sessionBean.getRoleid());

			// 删除没有权限子菜单
			int size = list.size();
			for (int i = size - 1; i >= 0; i--) {
				AdminMenu am = list.get(i);
				if ("1".equals(am.getMenuType()) && !isOreder(am.getId(), orederMenus)) {

					list.remove(i);
				}

			}
			List<RouteVo> voList = buildMenus(list, Contents.MENU_ROOT, "");

			// 删除没有子节点的目录
			modMenu(voList);
			
			info.setRouters(voList);

		}
		return RestResult.success(info);

	}
	public String modMenu(List<RouteVo> voList) {
		String redirect="";
		for (int i = voList.size() - 1; i >= 0; i--) {
			RouteVo rvo = voList.get(i);
			//如果是叶子不处理
			if(MenuType.SUBMENU.getType().equals(rvo.getMenutype())) {
					redirect=rvo.getPath();
				continue;
			}
			if (rvo.getChildren() != null && rvo.getChildren().size() > 0) {
				redirect=	modMenu(rvo.getChildren());
			rvo.setRedirect(redirect);
			} else {
				voList.remove(i);

			}

		}
		
		return redirect;
	}

	private boolean isOreder(String menuId, List<AdminRoleMenu> orederMenus) {
		int size = orederMenus.size();
		for (int i = size - 1; i >= 0; i--) {
			AdminRoleMenu rm = orederMenus.get(i);
			if (menuId.equals(rm.getMenuId())) {
				orederMenus.remove(i);
				return true;
			}
		}
		return false;
	}

	@RequestMapping(value = "logout", method = RequestMethod.POST)
	public RestResult login() throws DubboApiException {

		HttpSession session = ServletTools.getSession(false);
		if (session != null) {
			session.removeAttribute(Contents.SESSION_BEAN);
		}
		return RestResult.success();

	}

	private List<RouteVo> buildMenus(List<AdminMenu> source, String parentId, String path) {
		if (source != null && !source.isEmpty()) {
			List<RouteVo> list = new ArrayList<RouteVo>();

			source.forEach(value -> {
				if (value.getParentId().equals(parentId)) {
					RouteVo vo = new RouteVo();

					vo.setMenutype(value.getMenuType());
					vo.setName(value.getMenuName());
					vo.setPath(path + Contents.MENU_ROOT_PATH + value.getMenuPath());
					Meta meta = new Meta();
					meta.setIcon(value.getIcon());
					meta.setTitle(value.getMenuName());
					vo.setMeta(meta);
					if (Contents.MENU_ROOT.equals(value.getParentId())) {
						vo.setComponent(Contents.MENU_ROOT_COMPONENT);
					} else {
						vo.setComponent(value.getComponent());

					}

					// 当菜单 为目录需要添加子菜单
					if (vo.getMenutype().equals("0")) {
						vo.setChildren(buildMenus(source, value.getId(), vo.getPath()));

					}
					list.add(vo);
				}
			});
			return list;
		}

		return null;

	}

}
